package com.work.straighttalk.model;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.Gravity;
import android.widget.Toast;

import java.io.File;

/**
 * 此类用于uri and path之间的转化
 * Created by 朱相卿 on 16/3/18.
 */
public class PicUriTransformer {
    private ContentResolver cr;

    public PicUriTransformer(Context context) {
        cr = context.getContentResolver();
    }

    /**
     * 将选取图片的Uri 转化为String path
     *
     * @param selectedImageUri
     * @return
     */
    public String transPicUriToPath(final Uri selectedImageUri) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = cr.query(selectedImageUri, filePathColumn, null, null, null);
        if (cursor.moveToFirst()) {

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;
            if (picturePath == null || picturePath.equals("null")) {
                return null;
            }
            return picturePath;
        } else {
            File file = new File(selectedImageUri.getPath());
            if (!file.exists()) {
                return null;
            }
            return file.getAbsolutePath();
        }
    }

    /**
     * FilePathToUri
     * @param path
     * @return
     */
    public Uri FilePathToUri(String path) {

        if (path != null) {
            path = Uri.decode(path);
            StringBuffer buff = new StringBuffer();
            buff.append("(")
                    .append(MediaStore.Images.ImageColumns.DATA)
                    .append("=")
                    .append("'" + path + "'")
                    .append(")");
            Cursor cur = cr.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.ImageColumns._ID},
                    buff.toString(), null, null);
            int index = 0;
            for (cur.moveToFirst(); !cur.isAfterLast(); cur
                    .moveToNext()) {
                index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                // set _id value
                index = cur.getInt(index);
            }
            cur.close();
            cur = null;
            if (index == 0) {
                //do nothing
            } else {
                Uri uri_temp = Uri
                        .parse("content://media/external/images/media/"
                                + index);
                if (uri_temp != null) {
                    return uri_temp;
                }
            }

        }
        return null;
    }

}
